package com.logos.ruralrevitalization.service.impl;

import com.logos.ruralrevitalization.constant.RedisConstant;
import com.logos.ruralrevitalization.converter.ProductOrderConverter;
import com.logos.ruralrevitalization.entity.*;
import com.logos.ruralrevitalization.enums.IsDeleteFlagEnum;
import com.logos.ruralrevitalization.mapper.*;
import com.logos.ruralrevitalization.redis.RedisUtil;
import com.logos.ruralrevitalization.req.ProductOrderReq;
import com.logos.ruralrevitalization.resp.ShoppingCartResp;
import com.logos.ruralrevitalization.service.ProductOrderService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 农产品订单表(ProductOrder)表服务实现类
 *
 * @author rose
 * @since 2025-03-29 13:06:35
 */
@Service("productOrderService")
public class ProductOrderServiceImpl implements ProductOrderService {
    @Resource
    private ProductOrderMapper productOrderMapper;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private OrderCartMappingMapper orderCartMappingMapper;

    @Resource
    private AgriculturalProductMapper agriculturalProductMapper;

    @Resource
    private OrderProductMappingMapper orderProductMappingMapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public ProductOrder queryById(Long id) {
        return this.productOrderMapper.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param productOrder 筛选条件
     * @param pageRequest  分页对象
     * @return 查询结果
     */
    @Override
    public Page<ProductOrder> queryByPage(ProductOrder productOrder, PageRequest pageRequest) {
        long total = this.productOrderMapper.count(productOrder);
        return new PageImpl<>(this.productOrderMapper.queryAllByLimit(productOrder, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param productOrder 实例对象
     * @return 实例对象
     */
    @Override
    public ProductOrder insert(ProductOrder productOrder) {
        this.productOrderMapper.insert(productOrder);
        return productOrder;
    }

    /**
     * 修改数据
     *
     * @param productOrder 实例对象
     * @return 实例对象
     */
    @Override
    public ProductOrder update(ProductOrder productOrder) {
        this.productOrderMapper.update(productOrder);
        return this.queryById(productOrder.getId());
    }

    /**
     * 通过主键删除数据
     */
    @Override
    public boolean deleteById(Long id) {
        return this.productOrderMapper.deleteById(id) > 0;
    }

    /**
     * 下单
     */
    @Override
    @Transactional
    public Boolean add(ProductOrderReq productOrderReq) {
        ProductOrder productOrder = ProductOrderConverter.INSTANCE.convertReqToEntity(productOrderReq);
        // 利用redis的setNx自旋获取锁对象
        while (!redisUtil.setNx(RedisConstant.ORDER_LOCK, "logos", 2L, TimeUnit.SECONDS)) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        productOrderMapper.insert(productOrder);
        // 向订单购物车关系表中插入数据
        List<Long> shoppingCartIds = productOrderReq.getShoppingCartIds();
        List<OrderCartMapping> orderCartMappings = new LinkedList<>();
        for (Long shoppingCartId : shoppingCartIds) {
            OrderCartMapping orderCartMapping = new OrderCartMapping();
            orderCartMapping.setOrderId(productOrder.getId());
            orderCartMapping.setCartId(shoppingCartId);
            orderCartMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
            orderCartMappings.add(orderCartMapping);
        }
        orderCartMappingMapper.insertBatch(orderCartMappings);

        // 向订单农产品关系表中插入数据
        // 根据购物车id查询出所有的农产品id
        List<Long> productIds = shoppingCartIds.stream().map(shoppingCartId -> {
            ShoppingCart shoppingCart = shoppingCartMapper.queryById(shoppingCartId);
            return shoppingCart.getProductId();
        }).collect(Collectors.toList());
        List<OrderProductMapping> orderProductMappingList = new LinkedList<>();
        for (Long productId : productIds) {
            OrderProductMapping orderProductMapping = new OrderProductMapping();
            orderProductMapping.setProductId(productId);
            orderProductMapping.setOrderId(productOrder.getId());
            orderProductMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
            orderProductMappingList.add(orderProductMapping);
        }
        orderProductMappingMapper.insertBatch(orderProductMappingList);

        // 删除购物车中的数据
        int count = shoppingCartMapper.deleteBatch(shoppingCartIds);
        // 增加下单的农产品的销量
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.queryByIdList(shoppingCartIds);
        shoppingCartList.forEach(shoppingCartResp -> {
            Long productId = shoppingCartResp.getProductId();
            Integer quantity = shoppingCartResp.getQuantity();
            AgriculturalProduct agriculturalProduct = new AgriculturalProduct();
            agriculturalProduct.setId(productId);
            agriculturalProduct.setSalesVolume(quantity);
            agriculturalProductMapper.increment(agriculturalProduct);
        });

        // 删除缓存中与订单相关的数据
        removeCacheWithOrder();
        return count > 0;
    }

    private void removeCacheWithOrder() {
        // 获取所有符合模式的键
        List<String> keys = redisUtil.keys(RedisConstant.RURAL_SHOW + "*");
        // 删除这些键
        keys.forEach(key -> redisUtil.del(key));
    }
}
